<!-- 商品列表 -->
<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="goodsQueryRef"
      :inline="true"
      class="globalSerchFormStyle"
      label-width="80px"
    >
      <el-row>
        <el-col
          :span="6"
          v-if="['', null].includes($store.state.user.userLevel)"
        >
          <el-form-item label="油企名称" prop="enterpriseId" size="small">
            <el-select
              style="width: 190px"
              v-model="queryParams.enterpriseId"
              :clearable="true"
              filterable
              placeholder="请选择油企名称"
              @change="handleSelectChange"
            >
              <el-option
                v-for="(item, index) in enterpriseList"
                :key="index"
                :value="item.enterpriseId"
                :label="item.enterpriseName"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6" v-if="!['2'].includes($store.state.user.userLevel)">
          <el-form-item
            label="仓库/门店"
            prop="stationId"
            clearable
            size="small"
          >
            <el-select
              style="width: 190px"
              v-model="queryParams.stationId"
              :clearable="true"
              filterable
              placeholder="请选择仓库/门店"
            >
              <el-option
                v-for="item in stationList"
                :key="item.stationId"
                :label="item.stationName"
                :value="item.stationId"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="商品名称" prop="commodityName">
            <el-input
              v-model="queryParams.commodityName"
              placeholder="请输入商品名称"
              clearable
              size="small"
              style="width: 190px"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="商品编码" prop="commodityCode">
            <el-input
              v-model="queryParams.commodityCode"
              placeholder="请输入商品编码"
              clearable
              size="small"
              style="width: 190px"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="6">
          <el-form-item label="所属分类" prop="categoryId">
            <el-cascader
              v-model="queryCategoryIds"
              :options="categoryOptions"
              :props="{
                checkStrictly: true,
                label: 'categoryName',
                value: 'categoryId',
                children: 'children',
              }"
              filterable
              clearable
              size="small"
            ></el-cascader>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="创建时间" prop="dateRange">
            <el-date-picker
              v-model="datetimeRange"
              type="datetimerange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="yyyy-MM-dd HH:mm:ss"
              size="small"
              style="width: 190px"
            >
            </el-date-picker>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <!-- 按钮 -->
    <el-row :gutter="10" class="global_el_rowStyle">
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="getList"
        >
          搜索
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          icon="el-icon-refresh"
          size="mini"
          type="primary"
          @click="resetQuery"
        >
          重置
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          icon="el-icon-plus"
          size="mini"
          plain
          @click="handleGoods('add', {})"
        >
          新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          icon="el-icon-delete"
          size="mini"
          plain
          :disabled="selectionList.length <= 0"
          @click="deleteDialogVisible = true"
        >
          批量删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button size="mini" @click="toLeadInto" type="primary">
          导入
        </el-button>
      </el-col>
    </el-row>

    <!-- 导入 -->
    <el-dialog
      :title="upload.title"
      :visible.sync="upload.open"
      width="450px"
      style="text-align: center"
    >
      <el-upload
        ref="upload"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url"
        :on-success="handleFileSuccess"
        :on-change="handleFileChange"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">
          将文件拖到此处，或
          <em>点击上传</em>
        </div>
        <div class="el-upload__tip" slot="tip">
          <span style="color: red">
            提示：仅允许导入“xls”或“xlsx”格式文件！
          </span>
          <el-link
            type="info"
            style="font-size: 12px; margin-bottom: 3px"
            @click="importTemplate"
            >下载模板</el-link
          >
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button
          type="primary"
          @click="submitFileForm"
          :loading="uploadLoading"
          size="small"
          >确 定</el-button
        >
        <el-button @click="cancellation" size="small">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 批量入库错误 -->
    <el-dialog
      :title="upload.title"
      :visible.sync="fileUploadShow"
      width="45%"
      style="text-align: center"
    >
      <div class="dialog-table">
        <div style="margin-bottom: 30px">
          以下商品批量入库失败，请修改后再次提交。
        </div>
        <div class="tableInto-table">
          <el-table :data="tableInto" border>
            <el-table-column
              prop="num"
              label="序号"
              width="60"
            ></el-table-column>
            <el-table-column prop="commodityName" label="商品名称">
            </el-table-column>
            <el-table-column prop="reason" label="失败原因" width="200">
            </el-table-column>
          </el-table>
        </div>
      </div>

      <div slot="footer" class="dialog-footer">
        <el-button
          type="primary"
          plain
          @click="offUpload"
          size="small"
          round
          v-show="fileUploadShow"
        >
          关闭</el-button
        >
      </div>
    </el-dialog>

    <!-- table -->
    <el-table
      :data="goodListTable"
      style="width: 100%"
      @selection-change="handleSelectChange2"
      v-loading="loading"
      border
    >
      <el-table-column type="selection" width="50" align="left">
      </el-table-column>
      <el-table-column type="index" label="序号" width="50" align="left">
      </el-table-column>
      <el-table-column
        label="油企"
        align="left"
        prop="enterpriseName"
        v-if="[null].includes($store.state.user.userLevel)"
        width="150"
      >
      </el-table-column>
      <el-table-column
        v-if="!['2'].includes($store.state.user.userLevel)"
        prop="stationName"
        label="仓库/门店"
        width="150"
      >
      </el-table-column>
      <el-table-column prop="commodityName" label="商品名称" width="100">
      </el-table-column>
      <el-table-column prop="commodityCode" label="商品编码" width="180">
      </el-table-column>
      <el-table-column prop="barCode" label="商品条形码" width="100">
      </el-table-column>
      <el-table-column prop="categoryName" label="所属分类" width="100">
      </el-table-column>
      <el-table-column prop="retailPrice" label="进货价格(元)" width="100">
      </el-table-column>
      <el-table-column prop="salePrice" label="销售价格(元)" width="100">
      </el-table-column>
      <el-table-column prop="inventory" label="库存" width="100">
      </el-table-column>
      <el-table-column prop="unit" label="单位" width="100"> </el-table-column>
      <el-table-column prop="createTime" label="创建时间" width="180">
      </el-table-column>
      <el-table-column label="操作" fixed="right">
        <template slot-scope="scope">
          <el-button type="text" @click="handleGoods('detail', scope.row)"
            >查看</el-button
          >
          <el-button type="text" @click="handleGoods('edit', scope.row)"
            >编辑</el-button
          >
          <!-- <el-button type="text" @click="handlePutway(scope.row)"
            >上架</el-button
          > -->
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <pagination
      :hidden="total > 0 ? false : true"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
      :autoScroll="true"
    />

    <!-- 批量删除弹框 -->
    <el-dialog title="删除商品" :visible.sync="deleteDialogVisible" width="30%">
      <span>确定删除所选商品？</span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="deleteDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleDelete">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 商品上架 -->
    <GoodPutway
      :putwayDialog.sync="putwayDialog"
      :currentGoodInfo="currentGoodInfo"
      @reloadData="getList"
    ></GoodPutway>
  </div>
</template>
<script>
import { getToken } from "@/utils/auth";
import request from "@/utils/request_oil";
import {
  enterpriseList,
  listEnterpriseStation,
} from "@/api/nonOil/putlntoStorage";
import {
  getCommodityListApi,
  pathDeleteCommodityApi,
} from "@/api/nonOil/goods";
import { getNonOilCategoryTreeApi } from "@/api/nonOil/class";
import Treeselect from "@riophae/vue-treeselect";
import GoodPutway from "./productsList_putway.vue";
import { cloneDeep } from "lodash";
export default {
  name: "GoodList",
  components: { Treeselect, GoodPutway },
  data() {
    return {
      uploadLoading: false,
      tableInto: [],
      fileUploadShow: false,
      // 导入
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "批量导入",
        // 是否禁用上传
        isUploading: false,

        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_APIOIL + "/commodity/exportIn",
      },
      stationList: [],
      enterpriseList: [],
      total: 0,
      loading: false,
      queryCategoryIds: [],
      queryParams: {
        enterpriseId: null,
        stationId: null,
        pageNum: 1,
        pageSize: 10,
      },
      datetimeRange: [], // 搜索条件的时间范围
      goodListTable: [],
      categoryOptions: [], // 所属分类列表
      currentGoodInfo: {}, // 当前商品信息
      selectionList: [],
      deleteDialogVisible: false, // 删除弹框
      putwayDialog: false, // 上架弹框
    };
  },

  created() {
    // 油企
    if (this.presentEnterprise && this.presentEnterprise.enterpriseId) {
      this.queryParams.enterpriseId = this.presentEnterprise.enterpriseId;
      this.getStationList(this.queryParams.enterpriseId);
    }
    // 油站账号登录
    if (this.presentSation) {
      this.queryParams.stationId = this.presentSation;
    }
    this.getList();
    this.getNonOilCategoryList();
    this.getEnterpriseList();
  },
  methods: {
    // 点击导入
    toLeadInto() {
      this.upload.open = true;
    },

    // 关闭批量入库
    offUpload() {
      this.fileUploadShow = false;
    },

    // 点击下载模版
    async importTemplate() {
      let res = await request.get("/commodity/template", {
        responseType: "blob",
        withCredentials: false,
      });
      const fileExt = "xlsx";
      const filename = "导入模版" + (fileExt ? "." + fileExt : "");
      const blob = new Blob([res]);
      var downloadElement = document.createElement("a");
      var href = window.URL.createObjectURL(blob);
      downloadElement.href = href;
      downloadElement.download = filename;
      document.body.appendChild(downloadElement);
      downloadElement.click();
      document.body.removeChild(downloadElement);
      window.URL.revokeObjectURL(href);
    },

    // 文件上传
    handleFileChange(event, file, fileList) {
      console.log(1111111111, event, file, fileList);
      const fileDeep = cloneDeep(file);
      if (file.length > 1) {
        file.length = 0;
        file[0] = fileDeep[1];
      }
    },

    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      if (response.code == 500) {
        if (response.data) {
          this.tableInto = response.data;
          this.fileUploadShow = true;
        }
        this.$message.error(response.msg);
      } else {
        this.$message.success("批量入库成功");
      }
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.uploadLoading = false;
    },

    // 确认提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    },

    // 取消上传退出
    cancellation() {
      this.upload.open = false;
      this.$refs.upload.abort();
      this.$refs.upload.clearFiles();
      this.$message("已取消文件导入");
    },

    // 请选择油企
    handleSelectChange(value) {
      this.stationList = [];
      this.queryParams.stationId = null;
      this.getStationList(value);
    },

    // 查询油企
    getEnterpriseList() {
      enterpriseList().then((res) => {
        this.enterpriseList = res.rows;
      });
    },

    // 查询油站
    getStationList(val) {
      listEnterpriseStation({ enterpriseId: val, status: "1" }).then((res) => {
        this.stationList = res;
        // 判断单站，多站
        if (res.length <= 1) {
          this.isOnlyOneStation = true;
        }
        if (res.length === 1) {
          this.queryParams.stationId = res[0].stationId;
        }
      });
    },

    // 获取商品列表
    async getList() {
      this.loading = true;
      const params = { ...this.queryParams };
      if (this.datetimeRange && this.datetimeRange.length) {
        params.beginTime = this.datetimeRange[0];
        params.endTime = this.datetimeRange[1];
      }
      // 处理搜索条件中的分类id
      if (this.queryCategoryIds.length) {
        let ids = this.queryCategoryIds;
        params.categoryId = ids[ids.length - 1];
      }
      const res = await getCommodityListApi(params);
      this.loading = false;
      this.goodListTable = res.rows;
      this.total = res.total;
    },

    // 处理搜索条件中的所属分类数据
    handleCategoryOption(list) {
      const temlist = []; // 存放处理后的结果
      list.forEach((item) => {
        const obj = {};
        obj.categoryId = item.categoryId;
        obj.categoryName = item.categoryName;
        obj.value = item.categoryId;
        obj.label = item.categoryName;
        if (item.children && item.children.length > 0) {
          obj.children = this.handleCategoryOption(item.children); // 如果有children，则继续递归调用
        } else {
          obj.children = null; // children为空
        }
        temlist.push(obj);
      });
      return temlist;
    },

    // 获取分类列表
    async getNonOilCategoryList() {
      const res = await getNonOilCategoryTreeApi();
      this.categoryOptions = res.data.children;
      this.getNonOilData(this.categoryOptions);
    },

    getNonOilData(categoryOptions) {
      categoryOptions.forEach((item) => {
        if (!item.children.length) {
          item.children = null;
        } else {
          this.getNonOilData(item.children);
        }
      });
    },

    // 重置搜索表单
    resetQuery() {
      this.resetForm("goodsQueryRef");
      this.datetimeRange = [];
      this.queryCategoryIds = [];
      this.getList();
    },

    /** 转换菜单数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.categoryId,
        label: node.categoryName,
        children: node.children,
      };
    },

    // 增，改，查商品信息
    handleGoods(action, row) {
      this.currentGoodInfo = cloneDeep(row);
      this.$router.push({
        path: "/nonOil/productsList/productsList_add",
        query: {
          action,
          commodityForm: JSON.stringify(row),
        },
      });
    },

    // 选中行
    handleSelectChange2(selection) {
      this.selectionList = selection;
    },

    // 批量删除
    async handleDelete() {
      const ids = this.selectionList.map((item) => item.commodityId);
      await pathDeleteCommodityApi(ids);
      this.deleteDialogVisible = false;
      this.msgSuccess("删除商品成功");
      this.getList();
    },

    // 上架
    handlePutway(row) {
      this.currentGoodInfo = cloneDeep(row);
      this.putwayDialog = true;
    },
  },
};
</script>
<style scoped lang="scss"></style>
